﻿#include "LogHelper.h"
#include "qdebug.h"

QMutex LogLock;

Loghelper* Loghelper::Instance=0;

Loghelper* Loghelper::getInstance()
{
    if(Instance==0)
        Instance =new Loghelper();
    return Instance;
}
Loghelper::Loghelper(QObject *parent): QObject(parent)
{

}

//
Loghelper::~Loghelper()
{
}


void Loghelper:: WriteLog(QString type, QString content, int level)
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QString date= currentTime.toString("yyyyMMdd");


    if(level == 0){

        QString savePath="Logs/"+date;//存储路径 存当天日期路径下

        QDir dir;
        if (!(dir.exists(savePath)))
            dir.mkpath(savePath);

        LogLock.lock();
        QTime current_time = QTime::currentTime();
        QString fileName = savePath +"/"+ type + "_" +QString::number(current_time.hour())+".log";//日志类型(自定义) 后加上小时
        QString time = currentTime.toString("yyyy-MM-dd hh:mm:ss");
        QString data = content+" [" + time + "]" + " \n";//日志格式 日志内容后加上时间戳

        QFile f(fileName);
        f.open(QIODevice::WriteOnly|QIODevice::Append) ;
        QTextStream t(&f);
        t<<data;
        f.close();

        LogLock.unlock();
    }

    else if(level == 4){

        QString savePath="LogsJ/"+date;         //存储路径 存当天日期路径下

        QDir dir;
        if (!(dir.exists(savePath)))
            dir.mkpath(savePath);

        LogLock.lock();
        QTime current_time = QTime::currentTime();
        QString fileName = savePath +"/"+ type + "_" +QString::number(current_time.hour())+".log";//日志类型(自定义) 后加上小时
        QString time = currentTime.toString("yyyy-MM-dd hh:mm:ss");
        QString data = content+" [" + time + "]" + " \n";   //日志格式 日志内容后加上时间戳

        qDebug() << data;

        QFile f(fileName);
        f.open(QIODevice::WriteOnly|QIODevice::Append) ;
        QTextStream t(&f);
        t<<data;
        f.close();

        LogLock.unlock();
    }

}
